package com.atguigu.crowd.funding.interceptor;

import com.atguigu.crowd.funding.entity.Admin;
import com.atguigu.crowd.funding.entity.ResultEntity;
import com.atguigu.crowd.funding.util.CrowdFundingConstant;
import com.atguigu.crowd.funding.util.CrowdFundingUtils;
import com.google.gson.Gson;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author hftang
 * @date 2019-10-23 15:31
 * @desc 拦截器
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Admin admin = (Admin) request.getSession().getAttribute(CrowdFundingConstant.ATTR_NAME_LOGIN_ADMIN);

        if (admin == null) {

            // 进一步判断当前请求是否是异步请求
            boolean checkAsyncRequestResult = CrowdFundingUtils.checkAsyncRequest(request);
            if (checkAsyncRequestResult) {

                // 为异步请求的响应创建ResultEntity对象
                ResultEntity<String> resultEntity = ResultEntity.failed(ResultEntity.NO_DATA, CrowdFundingConstant.MESSAGE_ACCESS_DENIED);

                // 创建Gson对象
                Gson gson = new Gson();

                // 将ResultEntity对象转换为JSON字符串
                String json = gson.toJson(resultEntity);

                // 设置响应的内容类型
                response.setContentType("application/json;charset=UTF-8");

                // 将JSON字符串作为响应数据返回
                response.getWriter().write(json);

                // 表示不能放行，后续操作不执行
                return false;

            }


            //跳转到
            request.setAttribute(CrowdFundingConstant.ATTR_NAME_MESSAGE, CrowdFundingConstant.MESSAGE_ACCESS_DENIED);

            request.getRequestDispatcher("/WEB-INF/admin-login.jsp").forward(request, response);


            return false;
        }

        //返true 标示不拦截


        //返回false 标示拦截


        return true;
    }
}
